package com.guli.gulimall.product.service.impl;

import com.guli.gulimall.product.dao.AttrGroupDao;
import com.guli.gulimall.product.dao.CategoryDao;
import com.guli.gulimall.product.entity.AttrGroupEntity;
import com.guli.gulimall.product.entity.CategoryEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.guli.common.utils.PageUtils;
import com.guli.common.utils.Query;

import com.guli.gulimall.product.dao.AttrDao;
import com.guli.gulimall.product.entity.AttrEntity;
import com.guli.gulimall.product.service.AttrService;

@SuppressWarnings("all")
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrGroupDao attrGroupDao;
    @Autowired
    private CategoryDao categoryDao;
    @Override
    public PageUtils queryPage(String type,Long catelogId,Map<String, Object> params) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        if(type.equals("sale")){
            queryWrapper.eq("attr_type",0);
        }else{
            queryWrapper.eq("attr_type",1);
        }
        if(!catelogId.equals(0L)){
            queryWrapper.eq("catelog_id",catelogId);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );

        return new PageUtils(page);
    }
    @Override
    public List<AttrEntity> attrRelation(Long attrGroupId) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type",1);
        wrapper.eq("attr_group_id",attrGroupId);
        return baseMapper.selectList(wrapper);
    }

    @Override
    public PageUtils noattrRelation(Map<String, Object> params) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        wrapper.eq("attr_type",1);
        wrapper.isNull("attr_group_id");
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public boolean save(AttrEntity entity) {
        if(entity.getAttrGroupId()!=null){
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(entity.getAttrGroupId());
            entity.setAttrGroupName(attrGroupEntity.getAttrGroupName());
        }
        if(entity.getCatelogId()!=null){
            CategoryEntity categoryEntity = categoryDao.selectById(entity.getCatelogId());
            entity.setCatelogName(categoryEntity.getName());
        }
        return super.save(entity);
    }
}